package com.busi.controller.statistics;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.busi.model.GoodsArray;
import com.busi.model.OrderProducts;
import com.busi.model.OrderProductsStatistics;
import com.busi.model.OrderVo;
import com.busi.model.TotalMemberStatistics;
import com.busi.util.DateUtil;
import com.busi.util.HttpUtils;
import com.busi.util.MoneyUtil;
import com.busi.util.PropertyUtil;
import com.busi.util.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zcurd.controller.BaseController;

/**
 * ******************  类说明  *********************
 * class       :  OrederStatisticsController
 * @author     :  lihu
 * @version    :  1.0  
 * description :  用于数据统计（订单）  
 * @see        :     
 * @date       :  下午3:14:15
 * ***********************************************
 */
public class OrderStatisticsController extends BaseController{
	
	/**
	 * ********************************************
	 * method name   : listPage 
	 * description   : 跳转去商户明细表
	 * @return       : void
	 * @param        : 
	 * modified      : lihu ,  2017年4月18日  下午6:35:20
	 * @see          : 
	 * *******************************************
	 */
	public void listPage(){
		render("list.html");
	}
	
	
	/**
	 * ********************************************
	 * method name   : totallistPage 
	 * description   : 商户结算汇总表
	 * @return       : void
	 * @param        : 
	 * modified      : lihu ,  2017年4月18日  下午6:36:01
	 * @see          : 
	 * *******************************************
	 */
	public void  totallistPage(){
		render("totallist.html");
	}
	
	
	/**
	 * ********************************************
	 * method name   : totalList 
	 * description   : 商户汇总表 页面展示
	 * @return       : void
	 * @param        : 
	 * modified      : lihu ,  2017年4月18日  下午6:36:50
	 * @see          : 
	 * *******************************************
	 */
	public void totalList(){
		LOG.debug("#exportMerTable() 商品汇总查询开始");
		OrderProducts orderproduct = getBean(OrderProducts.class, "");
		if (StringUtil.isBlank(orderproduct.get_start_time()) || StringUtil.isBlank(orderproduct.get_end_time())) {
			
			orderproduct.set_start_time(DateUtil.getOneMonthAgO());
			orderproduct.set_end_time(DateUtil.getNowDate2());
		}
		String body = gson.toJson(orderproduct);
		LOG.info("#exportMerTable() 调用订单查询接口，请求报文:" + body);
		String domain = PropertyUtil.getStrValue("platform.domain", "");
		String url = domain + "/emall/admin/order/statistic/querytotallistdata";
		String[][] headers = {{"Content-Type", "application/json"}};
		String respjson = HttpUtils.doPost(url, body, headers, 3, 5, "utf-8");
		LOG.info("#exportMerTable() 调用订单查询接口查询订单，响应报文:" + respjson);
		
	    Gson gson = new Gson();
//	    BigDecimal totalAcount = new BigDecimal("0");//结算总价
//	    BigDecimal mayAcount = new BigDecimal("0");//应结算金额
//	    BigDecimal refundAcount = new BigDecimal("0");//退款总额
//	    BigDecimal shouldAcount = new BigDecimal("0");//可结算金额
	    //订单格式转换 订单信息统计
	    //响应转换成商品订单信息
	    //查询响应是订单明细
	    List<GoodsArray> exportlist = gson.fromJson(respjson, new TypeToken<List<GoodsArray>>() {}.getType() );
	    //创建Map 根据KEY值确保商户号相同的进行统计
	    Map<String,TotalMemberStatistics> map = new HashMap<String, TotalMemberStatistics>();
	    for (GoodsArray goodsArray : exportlist) {
				if (null == map.get(goodsArray.getMerid())) {
					//如果这个供货商没有被统计到 在设置他的信息
					TotalMemberStatistics ttlm = new TotalMemberStatistics();
					//订单结算日期  暂定以当前日期  
					ttlm.setBalancedate(DateUtil.changeDate(DateUtil.getReqDate()));
					//根据他的筛选条件 获取结算区间  默认为所有订单  
					if (StringUtil.isNotBlank(orderproduct.get_start_time()) && StringUtil.isNotBlank(orderproduct.get_end_time())) {
						ttlm.setSettlementrange(orderproduct.get_start_time() + "至" + orderproduct.get_end_time());
					}else {
						ttlm.setSettlementrange("");
					}
					//设置供货商编号
					ttlm.setMerid(goodsArray.getMerid());
					//设置商户名
					ttlm.setMername(goodsArray.getMername());
					//设置订单价格
					ttlm.setOrderprice(goodsArray.getOrderprice());
					//设置应该结算价格
					ttlm.setTotalmaystaprice(goodsArray.getMaystaprice());
					//设置退款价格
					ttlm.setTotalreimburse(goodsArray.getReimburse());
					//设置真是退款的价格
					ttlm.setTotalrealprice(goodsArray.getRealpirce());
					//把商户放入到Map  避免同ID商户的覆盖  
					map.put(goodsArray.getMerid(), ttlm);
				}else {
					//如果 获取供货商 已存在   这个 供货商 有多笔订单  根据之前的明细结果 做累加
					TotalMemberStatistics ttlm = map.get(goodsArray.getMerid());
					//通过方法 进行累加  这个方法 不能携带  小数位  计量单位分  
					// 前台进行 格式转换
					//订单金额累加
					ttlm.setOrderprice(MoneyUtil.sAndSAdd(ttlm.getOrderprice(), goodsArray.getOrderprice()));
					//应结算金额累加
					ttlm.setTotalmaystaprice(MoneyUtil.sAndSAdd(ttlm.getTotalmaystaprice(),goodsArray.getMaystaprice()));
					//退款金额累加
					ttlm.setTotalreimburse(MoneyUtil.sAndSAdd(ttlm.getTotalreimburse(),goodsArray.getReimburse()));
					//实际结算金额累加
					ttlm.setTotalrealprice(MoneyUtil.sAndSAdd(ttlm.getTotalrealprice(), goodsArray.getRealpirce()));
				}
				
			}
	    //用map返回数据
	    Map<String,Object> resp = new HashMap<String, Object>();
	    //从 存放商户信息的map中获取List
	    List<TotalMemberStatistics> list = new ArrayList<TotalMemberStatistics>(map.values());
	    resp.put("total", list.size());
	    resp.put("rows", list);
		renderJson(resp);
	}
	
	
	/**
	 * ********************************************
	 * method name   : exportTotalMerTable 
	 * description   : 导出获取商户汇总信息 
	 * @return       : void
	 * @param        : @throws Exception
	 * modified      : lihu ,  2017年4月18日  下午8:05:28
	 * @see          : 
	 * *******************************************
	 */
	public void exportTotalMerTable() throws Exception{
		LOG.debug("#exportMerTable() 显示线上查询订单表");
		//或页面参数
		OrderProducts orderproduct = getBean(OrderProducts.class, "");
		// 参数转化成json 
		String body = gson.toJson(orderproduct);
		LOG.info("#exportMerTable() 调用订单查询接口，请求报文:" + body);
		String domain = PropertyUtil.getStrValue("platform.domain", "");
		String url = domain + "/emall/admin/order/statistic/totalexportlistdata";
		String[][] headers = {{"Content-Type", "application/json"}};
		String respjson = HttpUtils.doPost(url, body, headers, 3, 5, "utf-8");
		LOG.info("#exportMerTable() 调用订单查询接口，响应报文:" + respjson);
	    Gson gson = new Gson();
	    LOG.info("#exportTotalMerTable() 组织到导出信息");
	    String totalAcount = "0";//结算总价
	    String mayAcount = "0";//应结算金额
	    String refundAcount = "0";//退款总额
	    String shouldAcount = "0";//可结算金额
	    //订单格式转换 订单信息统计
	    List<GoodsArray> exportlist = gson.fromJson(respjson, new TypeToken<List<GoodsArray>>() {}.getType() );
	    //商户汇总统计步骤 
	    Map<String,TotalMemberStatistics> map = new HashMap<String, TotalMemberStatistics>();
	    for (GoodsArray goodsArray : exportlist) {
				if (null == map.get(goodsArray.getMerid())) {
					TotalMemberStatistics ttlm = new TotalMemberStatistics();
					ttlm.setBalancedate(DateUtil.changeDate(DateUtil.getReqDate()));
					if (StringUtil.isNotBlank(orderproduct.get_start_time()) && StringUtil.isNotBlank(orderproduct.get_end_time())) {
						ttlm.setSettlementrange(orderproduct.get_start_time() + "至" + orderproduct.get_end_time());
					}else {
						ttlm.setSettlementrange("");
					}
					
					ttlm.setMerid(goodsArray.getMerid());
					ttlm.setMername(goodsArray.getMername());
					ttlm.setOrderprice(goodsArray.getOrderprice());
					ttlm.setTotalmaystaprice(goodsArray.getMaystaprice());
					ttlm.setTotalreimburse(goodsArray.getReimburse());
					ttlm.setTotalrealprice(goodsArray.getRealpirce());
					map.put(goodsArray.getMerid(), ttlm);
				}else {
					TotalMemberStatistics ttlm = map.get(goodsArray.getMerid());
					ttlm.setOrderprice(MoneyUtil.sAndSAdd(ttlm.getOrderprice(), goodsArray.getOrderprice()));
					ttlm.setTotalmaystaprice(MoneyUtil.sAndSAdd(ttlm.getTotalmaystaprice(),goodsArray.getMaystaprice()));
					ttlm.setTotalreimburse(MoneyUtil.sAndSAdd(ttlm.getTotalreimburse(),goodsArray.getReimburse()));
					ttlm.setTotalrealprice(MoneyUtil.sAndSAdd(ttlm.getTotalrealprice(), goodsArray.getRealpirce()));
				}
				
				
			}
	    
	    List<TotalMemberStatistics> list = new ArrayList<TotalMemberStatistics>(map.values());
	    //数据导出页面格式转换
	    for (TotalMemberStatistics ttlms : list) {
	    	totalAcount = MoneyUtil.sAndSAdd(totalAcount, ttlms.getOrderprice());
	    	ttlms.setOrderprice(MoneyUtil.Cent2Dollar(ttlms.getOrderprice()));
			mayAcount = MoneyUtil.sAndSAdd(mayAcount, ttlms.getTotalmaystaprice());
			ttlms.setTotalmaystaprice(MoneyUtil.Cent2Dollar(ttlms.getTotalmaystaprice()));
			refundAcount = MoneyUtil.sAndSAdd(refundAcount, ttlms.getTotalreimburse());
			ttlms.setTotalreimburse(MoneyUtil.Cent2Dollar(ttlms.getTotalreimburse()));
			shouldAcount = MoneyUtil.sAndSAdd(shouldAcount, ttlms.getTotalrealprice());
			ttlms.setTotalrealprice(MoneyUtil.Cent2Dollar(ttlms.getTotalrealprice()));
	    }
	    
	    String filename = "商户结算汇总明细表" + DateUtil.getNowDate() + ".xls";
	    //统计金额格式转换
	    totalAcount = MoneyUtil.Cent2Dollar(totalAcount);
	    mayAcount = MoneyUtil.Cent2Dollar(mayAcount);
	    refundAcount = MoneyUtil.Cent2Dollar(refundAcount);
	    shouldAcount = MoneyUtil.Cent2Dollar(shouldAcount);
	    //组织返回信息
	    setAttr("totalAcount", totalAcount);
	    setAttr("mayAcount", mayAcount);
	    setAttr("refundAcount", refundAcount);
	    setAttr("shouldAcount", shouldAcount);
		setAttr("exportlist", list);
		//设置响应头
		getResponse().setContentType("application/msexcel;charset=UTF-8"); 
		getResponse().setHeader("Content-disposition","attachment; " +
				"filename=" + java.net.URLEncoder.encode(filename , "UTF-8"));
		render("totalexport.html");
		
	}
	
	
	
	
	
	
	
	
	/**
	 * ********************************************
	 * method name   : exportMerTable 
	 * description   : 导出会员明细表
	 * @return       : void
	 * @param        : @throws Exception
	 * modified      : lihu ,  2017年4月18日  下午8:09:37
	 * @see          : 
	 * *******************************************
	 */
	public void exportMerTable() throws Exception{
		LOG.debug("#exportMerTable() 显示线上查询订单表");
		OrderProducts orderproduct = getBean(OrderProducts.class, "");
		String body = gson.toJson(orderproduct);
		LOG.info("#exportMerTable() 调用订单查询接口，请求报文:" + body);
		String domain = PropertyUtil.getStrValue("platform.domain", "");
		String url = domain + "/emall/admin/order/statistic/exportlistdate";
		String[][] headers = {{"Content-Type", "application/json"}};
		String respjson = HttpUtils.doPost(url, body, headers, 3, 5, "utf-8");
		LOG.info("#exportMerTable() 调用订单查询接口，响应报文:" + respjson);
		
	    Gson gson = new Gson();
	    LOG.info("组织到导出信息");
	    BigDecimal totalAcount = new BigDecimal("0");//结算总价
	    BigDecimal mayAcount = new BigDecimal("0");//应结算金额
	    BigDecimal refundAcount = new BigDecimal("0");//退款总额
	    BigDecimal shouldAcount = new BigDecimal("0");//可结算金额
	    //订单格式转换 订单信息统计 （每笔订单）
	    List<GoodsArray> exportlist = gson.fromJson(respjson, new TypeToken<List<GoodsArray>>() {}.getType() );
	    	for (GoodsArray goodsArray : exportlist) {
	    		//订单日期转换
				goodsArray.setOrderdate(DateUtil.changeDate(goodsArray.getOrderdate()));
				//签收日期
				goodsArray.setDelivetimestr(DateUtil.getLongDateStr(goodsArray.getDelivetime()));
				//用于 展示的订单生成时间（订单入库时间） 
				goodsArray.setShowintime(DateUtil.getLongDateStr(goodsArray.getIntime()));
				//修改时间 处理后
				goodsArray.setModtimestr(DateUtil.getLongDateStr(goodsArray.getModtime()));
				//订单金额
				goodsArray.setOrderprice(MoneyUtil.Cent2Dollar(goodsArray.getOrderprice()));
				// 市场价
				goodsArray.setMarketprice(MoneyUtil.Cent2Dollar(MoneyUtil.fixMoney(goodsArray.getMarketprice(),0)));
				//进货价结算价
				goodsArray.setPurchaserprice(MoneyUtil.Cent2Dollar(MoneyUtil.fixMoney(goodsArray.getPurchaserprice(),0)));
				//应结算价
				goodsArray.setMaystaprice(MoneyUtil.Cent2Dollar(goodsArray.getMaystaprice()));
				// 总结算价
				totalAcount = totalAcount.add(goodsArray.getPurchaserprice());
				//应结算价格
				mayAcount = mayAcount.add(new BigDecimal(goodsArray.getMaystaprice()));
				goodsArray.setReimburse(MoneyUtil.Cent2Dollar(goodsArray.getReimburse()));
				//总退货价
				refundAcount = refundAcount.add(new BigDecimal(goodsArray.getReimburse()));
				//实际结算价
				goodsArray.setRealpirce(MoneyUtil.Cent2Dollar(goodsArray.getRealpirce()));
				shouldAcount  = shouldAcount.add(new BigDecimal(goodsArray.getRealpirce()));
			}
	    
	    
	    String filename = "商户结算明细表" + DateUtil.getNowDate() + ".xls";
	    
	    setAttr("totalAcount", totalAcount);
	    setAttr("mayAcount", mayAcount);
	    setAttr("refundAcount", refundAcount);
	    setAttr("shouldAcount", shouldAcount);
		setAttr("exportlist", exportlist);
		getResponse().setContentType("application/msexcel;charset=UTF-8"); 
		getResponse().setHeader("Content-disposition","attachment; " +
				"filename=" + java.net.URLEncoder.encode(filename , "UTF-8"));
		render("export.html");
		
	}
	
	public void listData(){
		LOG.debug("#listData() 显示线上查询订单表");
		OrderProducts orderproduct = getBean(OrderProducts.class, "");
		String body = gson.toJson(orderproduct);
		LOG.info("#listData() 调用订单查询接口，请求报文:" + body);
		String domain = PropertyUtil.getStrValue("platform.domain", "");
		String url = domain + "/emall/admin/order/statistic/querylistdate";
		String[][] headers = {{"Content-Type", "application/json"}};
		String respjson = HttpUtils.doPost(url, body, headers, 3, 5, "utf-8");
		LOG.info("#listData() 调用订单查询接口，响应报文:" + respjson);

		if (respjson == null) {
			LOG.info("#listData()  统计查询响应为空");
		}
		
		renderJson(respjson);
	}
	
}
